﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OpenIdRelyingPartyWebForms;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy;
using System.Net;
using System.Web.Script.Serialization;
using DataAccess;
using System.Net.NetworkInformation;
namespace SQT.tracnghiem.Ajax.ASP
{
    public partial class Google_login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string url = Request.Url.AbsoluteUri;

            if (url.Contains("access_token"))
            {

                string accessToken = Request.QueryString["access_token"];
                //string requestUrl = "https://graph.facebook.com/me?access_token=" + accessToken;
                string requestUrl = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;
                WebClient client = new WebClient();
                string userInformation = client.DownloadString(requestUrl);


                JavaScriptSerializer jss = new JavaScriptSerializer();
                var user = jss.Deserialize<GoogleUserInfo>(userInformation);

                string gg_username = "gg" + user.id;
                if (user != null)
                {
                    string MAC = "";
                    NetworkInterface[] DanhSachCardMang = NetworkInterface.GetAllNetworkInterfaces();
                    for (int i = 0; i < 1; i++)
                    {
                        PhysicalAddress DiaChiMAC = DanhSachCardMang[i].GetPhysicalAddress();
                        //MAC += DanhSachCardMang[i].Name + " : ";
                        byte[] ByteDiaChi = DiaChiMAC.GetAddressBytes();
                        for (int j = 0; j < ByteDiaChi.Length; j++)
                        {
                            MAC += ByteDiaChi[j].ToString("X2");
                            if (j != ByteDiaChi.Length - 1)
                            {
                                MAC += "-";
                            }
                        }
                    }

                    var find_user = new TblUserController().FetchAll().Where(x => x.UserName.ToLower() == gg_username.ToLower()).ToList();

                    if (find_user.Count == 0)
                    {
                        DateTime birthday = DateTime.Parse("1/1/1990");
                        bool sex = true;
                        if (user.gender == "female")
                            sex = false;
                        //if (user.birthday != null)
                        //    birthday = user.birthday;
                        var get_role = new TblUserRoleController().FetchAll().First();
                        new TblUserController().Insert("",gg_username, "sqt123456789", user.name, birthday, "", "userpic.png", user.email,null, null, "", sex, get_role.RoleId, null, true, DateTime.Now, "headerbanner.jpg", "");
                        var get_user = new TblUserController().FetchAll().Where(x => x.UserName.ToLower() == gg_username.ToLower()).Single();
                        Session["user"] = get_user.UserName;
                        Session["level"] = get_user.UserLevel;
                        Session["user_id"] = get_user.UserId;
                        HttpCookie ck = new HttpCookie("user");
                        ck.Value = get_user.UserId.ToString();
                        Response.Cookies.Add(ck);
                    }
                    else
                    {
                        var get_user = new TblUserController().FetchAll().Where(x => x.UserName.ToLower() == gg_username.ToLower()).Single();
                        new TblUserController().Update(get_user.UserId, get_user.NumberStudy, get_user.UserName, get_user.UserPass, user.name, get_user.BirthDay, get_user.Phone, get_user.Avatar, get_user.Email, get_user.AddressMail, get_user.Address, get_user.Facebook, get_user.Sex, get_user.UserLevel,get_user.ClassX, get_user.Active, get_user.SignInDate,get_user.Wallpaper, get_user.Note);

                        Session["user"] = get_user.UserName;
                        Session["level"] = get_user.UserLevel;
                        Session["user_id"] = get_user.UserId;
                        HttpCookie ck = new HttpCookie("user");
                        ck.Value = get_user.UserId.ToString();
                        Response.Cookies.Add(ck);
                    }
                }


                //Dong trang dang nhap
                Response.Redirect("~/ajax/asp/CloseTab.aspx");
            }

            else
                if (url.Contains("error"))
                    Response.Write("Có lỗi trong quá trình đăng nhập. <a href=\"javascript:window.close();\">Đóng cửa sổ</a>");

        }
        public class GoogleUserInfo
        {
            public GoogleUserInfo()
            {
                //
                // TODO: Add constructor logic here
                //
            }

            public string id { get; set; }
            public string name { get; set; }
            public string email { get; set; }
            public string first_name { get; set; }
            public string last_name { get; set; }
            public string address { get; set; }
            public string link { get; set; }
            public string username { get; set; }
            public string gender { get; set; }
            public string timezone { get; set; }
            public string locale { get; set; }
            public string verified { get; set; }
            public string updated_time { get; set; }
            public DateTime birthday { get; set; }
            //location {}
            //work {}
            //education{}

        }
    }
}